package com.wr.auth.common.service;

import com.wr.api.system.domain.LoginUser;
import com.wr.api.system.service.RemoteSystemService;
import com.wr.auth.domain.LoginForm;
import com.wr.common.core.constants.Constants;
import com.wr.common.core.exception.ServiceException;
import com.wr.common.core.utils.StringUtils;
import com.wr.common.core.utils.uuid.IdUtils;
import com.wr.common.redis.constants.CacheConstants;
import com.wr.common.redis.service.RedisService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author MyPC
 */
@Component
public class MailboxService {

    @Autowired
    private RemoteSystemService remoteUserService;

    @Autowired
    private RedisService redisService;

    public Map<String, String> getCode(String ak) {
        Map<String, String> map = new HashMap<>(2);
        //先获取手机号缓存，如果存在。则证明此手机号在60s内
        if (StringUtils.isNotNull(redisService.getCacheObject(ak))) {
            throw new ServiceException("请60秒后重试");
        }
        //发送验证码工具类
        String ckId = IdUtils.simpleUuid();
        String ck = IdUtils.getFourNum().toString();
        //将验证码放入缓存
        redisService.setCacheObject(CacheConstants.MAILBOX_CODE_KEY + ckId, ck, Constants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        //将邮箱缓存60秒
        redisService.setCacheObject(ak, ck, 60L, TimeUnit.SECONDS);
        map.put("ckId", ckId);
        map.put("ck", ck);
        map.put("expireTime", Constants.CAPTCHA_EXPIRATION + "分钟");
        return map;
    }

    public LoginUser getLoginUser(LoginForm loginForm) {
        isCodeLose(loginForm.getAk(), loginForm.getCkId(), loginForm.getCk());
        return remoteUserService.getUserInfoByMailbox(loginForm.getAk(), true).getData();
    }

    private void isCodeLose(String ak, String ckId, String ck) {
        //如果是短信登录，校验验证码
        String conCode = redisService.getCacheObject(CacheConstants.MAILBOX_CODE_KEY + ckId);
        if (StringUtils.isEmpty(conCode)) {
            throw new ServiceException("验证码已失效");
        }
        //校验手机号，校验通过清除缓存
        if (ck.equals(conCode)) {
            redisService.deleteObject(CacheConstants.MAILBOX_CODE_KEY + ckId);
            redisService.deleteObject(ak);
        } else {
            throw new ServiceException("验证码错误");
        }
    }
}
